

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="深海火锅店">
  <meta name="keywords" content="">
  
    <meta name="description" content="表单校验JSR303 1234&lt;dependency&gt;   &lt;groupId&gt;org.springframework.boot&lt;&#x2F;groupId&gt;    &lt;artifactId&gt;spring-boot-starter-validation&lt;&#x2F;artifactId&gt;&lt;&#x2F;dependency&gt;   给Bean添加校验注解 如@Em">
<meta property="og:type" content="article">
<meta property="og:title" content="表单校验+异常处理">
<meta property="og:url" content="http://example.com/2023/02/18/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/Java/%E5%AD%A6%E4%B9%A0/%E6%A1%86%E6%9E%B6/SpringBoot/%E8%A1%A8%E5%8D%95%E6%A0%A1%E9%AA%8C+%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="表单校验JSR303 1234&lt;dependency&gt;   &lt;groupId&gt;org.springframework.boot&lt;&#x2F;groupId&gt;    &lt;artifactId&gt;spring-boot-starter-validation&lt;&#x2F;artifactId&gt;&lt;&#x2F;dependency&gt;   给Bean添加校验注解 如@Em">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181408949.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181409557.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181430162.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181430912.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181432950.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181436807.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181448835.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181508917.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181523120.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181534110.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181535976.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181536074.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181536000.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181554598.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181612517.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181612589.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181613521.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181620912.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181625320.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181645029.png">
<meta property="article:published_time" content="2023-02-18T09:12:00.000Z">
<meta property="article:modified_time" content="2024-02-15T16:04:19.051Z">
<meta property="article:author" content="深海火锅店">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181408949.png">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>表单校验+异常处理 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fluid</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/background.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="表单校验+异常处理"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-02-18 17:12" pubdate>
          2023年2月18日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          11k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          91 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">表单校验+异常处理</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="表单校验"><a href="#表单校验" class="headerlink" title="表单校验"></a>表单校验</h2><p><code>JSR303</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>   <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-validation<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>

<ol>
<li><p>给Bean添加校验注解</p>
<p>如<code>@Email</code> 标注的字段为邮箱、<code>@NotNull</code> 标注的字段不能为空、<code>@Future</code> 标注的字段必须是未来的时间、<code>@Min</code>标注最小值</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 若不写message，则返回默认信息</span><br><span class="hljs-meta">@NotBlank(message = &quot;用户名不能为空&quot;)</span><br><span class="hljs-meta">@TableField(value = &quot;username&quot;)</span><br><span class="hljs-keyword">private</span> String username;<br></code></pre></td></tr></table></figure>


</li>
<li><p>开启校验注解<code>@Valid</code>，告知spring方法需要开启校验这些字段，上面只是标注了校验规则，标注<code>（@Valid）</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@PostMapping(&quot;/test&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">test</span><span class="hljs-params">(<span class="hljs-meta">@Valid</span> <span class="hljs-meta">@RequestBody</span> User user)</span>&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;error1&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>获取校验的结果，校验是否成功…，紧跟参数后面添加<code>BindingResult result</code>，示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@PostMapping(&quot;/test&quot;)</span><br><span class="hljs-keyword">public</span> Object <span class="hljs-title function_">test</span><span class="hljs-params">(<span class="hljs-meta">@Valid</span> <span class="hljs-meta">@RequestBody</span> User user, BindingResult result)</span>&#123;<br>    Map&lt;String, Object&gt; map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>    <span class="hljs-comment">// 如果校验出错</span><br>    <span class="hljs-keyword">if</span> (result.hasErrors())&#123;<br>        Map&lt;String, String&gt; error = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>        <span class="hljs-comment">// 获取校验的错误结果</span><br>            result.getFieldErrors().forEach((item)-&gt;&#123;<br>        <span class="hljs-comment">// FieldError 获取到错误提示</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">message</span> <span class="hljs-operator">=</span> item.getDefaultMessage();<br>        <span class="hljs-comment">// 获取错误的属性名字</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">field</span> <span class="hljs-operator">=</span> item.getField();<br>        error.put(field,message);<br>        &#125;);<br>        map.put(<span class="hljs-string">&quot;code&quot;</span>,<span class="hljs-number">500</span>);<br>        map.put(<span class="hljs-string">&quot;message&quot;</span>,error);<br>    &#125;<span class="hljs-keyword">else</span>&#123;<br>        <span class="hljs-comment">// 校验未出错</span><br>        map.put(<span class="hljs-string">&quot;code&quot;</span>,<span class="hljs-number">200</span>);<br>        map.put(<span class="hljs-string">&quot;message&quot;</span>,user);<br>    &#125;<br>    <span class="hljs-keyword">return</span> map;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181408949.png" srcset="/img/loading.gif" lazyload alt="image-20230218140813717"></p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181409557.png" srcset="/img/loading.gif" lazyload alt="image-20230218140908480"></p>
</li>
</ol>
<h3 id="自定义校验规则"><a href="#自定义校验规则" class="headerlink" title="自定义校验规则"></a>自定义校验规则</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// regexp内写 正则表达式    </span><br><span class="hljs-meta">@Pattern(regexp = &quot;/^[a-zA-Z0-9]$/&quot;,message = &quot;昵称必须是一个字母或数字&quot;)</span><br><span class="hljs-meta">@TableField(value = &quot;nick_name&quot;)</span><br><span class="hljs-keyword">private</span> String nick_name;<br></code></pre></td></tr></table></figure>

<h2 id="配置全局异常处理"><a href="#配置全局异常处理" class="headerlink" title="配置全局异常处理"></a>配置全局异常处理</h2><blockquote>
<ol>
<li><p>类添加注解</p>
<ul>
<li><p>@ControllerAdvice 如果需要返回json数据，则需要在方法上加上@ResponseBody</p>
</li>
<li><p>@RestControllerAdvice，默认返回json数据，方法不需要加@ResponseBody</p>
<p><code>区别</code>:参考@RestController和@Controller的</p>
</li>
</ul>
</li>
<li><p>方法添加处理器</p>
<ul>
<li><p>捕获全局异常，处理所有不可知异常</p>
</li>
<li><p>@ExceptionHandler(value&#x3D;Exception.class)</p>
</li>
</ul>
</li>
</ol>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> lombok.extern.slf4j.Slf4j;<br><span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.ExceptionHandler;<br><span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.RestControllerAdvice;<br><br><span class="hljs-meta">@Slf4j</span><br><span class="hljs-meta">@RestControllerAdvice(basePackages = &quot;com.example.exceptiontest.controller&quot;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserExceptionControllerAdvice</span> &#123;<br>    <span class="hljs-meta">@ExceptionHandler(value = Exception.class)</span><br>    <span class="hljs-keyword">public</span> Object <span class="hljs-title function_">handleValidException</span><span class="hljs-params">(Exception e)</span>&#123;<br>        HashMap&lt;String, String&gt; map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>        map.put(<span class="hljs-string">&quot;message&quot;</span>,e.getMessage());<br>        map.put(<span class="hljs-string">&quot;class&quot;</span>,e.getClass().toString());<br>        log.error(<span class="hljs-string">&quot;数据校验出现异常:&#123;&#125;，异常类型:&#123;&#125;&quot;</span>,e.getMessage(),e.getClass());<br>        <span class="hljs-keyword">return</span> map;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>既然要进行异常处理，那么上方配置的校验就需要抛出异常，去掉BindingResult即可</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@PostMapping(&quot;/test2&quot;)</span><br><span class="hljs-keyword">public</span> Object <span class="hljs-title function_">test2</span><span class="hljs-params">(<span class="hljs-meta">@Valid</span> <span class="hljs-meta">@RequestBody</span> User user)</span>&#123;<br>    Map&lt;String, Object&gt; map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>    map.put(<span class="hljs-string">&quot;code&quot;</span>,<span class="hljs-number">200</span>);<br>    map.put(<span class="hljs-string">&quot;message&quot;</span>,user);<br>    <span class="hljs-keyword">return</span> map;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181430162.png" srcset="/img/loading.gif" lazyload alt="image-20230218143001936"></p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181430912.png" srcset="/img/loading.gif" lazyload alt="image-20230218143053836"></p>
<blockquote>
<p>指定的异常类型需要更精确才行</p>
</blockquote>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181432950.png" srcset="/img/loading.gif" lazyload alt="image-20230218143237871"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Slf4j</span><br><span class="hljs-meta">@RestControllerAdvice(basePackages = &quot;com.example.exceptiontest.controller&quot;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserExceptionControllerAdvice</span> &#123;<br>    <span class="hljs-meta">@ExceptionHandler(value = MethodArgumentNotValidException.class)</span><br>    <span class="hljs-keyword">public</span> Object <span class="hljs-title function_">handleValidException</span><span class="hljs-params">(MethodArgumentNotValidException e)</span>&#123;<br>        HashMap&lt;String, String&gt; map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>        <span class="hljs-type">BindingResult</span> <span class="hljs-variable">bindingResult</span> <span class="hljs-operator">=</span> e.getBindingResult();<br>        map.put(<span class="hljs-string">&quot;code&quot;</span>,<span class="hljs-string">&quot;400&quot;</span>);<br>        bindingResult.getFieldErrors().forEach((item)-&gt;&#123;<br>            map.put(item.getField(),item.getDefaultMessage());<br>        &#125;);<br>        map.put(<span class="hljs-string">&quot;msg&quot;</span>,<span class="hljs-string">&quot;数据校验出现异常&quot;</span>);<br>        log.error(<span class="hljs-string">&quot;数据校验出现异常:&#123;&#125;，异常类型:&#123;&#125;&quot;</span>,e.getMessage(),e.getClass());<br>        <span class="hljs-keyword">return</span> map;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181436807.png" srcset="/img/loading.gif" lazyload alt="image-20230218143612705"></p>
<blockquote>
<p>为了更加统一、方便地编写返回状态码，可创建一个<code>枚举类</code></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title class_">BizCodeEnume</span> &#123;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 系统未知异常</span><br><span class="hljs-comment">     */</span><br>    UNKNOWN_EXCEPTION(<span class="hljs-number">10000</span>,<span class="hljs-string">&quot;系统未知异常&quot;</span>),<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 参数格式校验失败</span><br><span class="hljs-comment">     */</span><br>    VAILD_EXCEPTION(<span class="hljs-number">10001</span>,<span class="hljs-string">&quot;参数格式校验失败&quot;</span>);<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> code;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> String msg;<br>    BizCodeEnume(<span class="hljs-type">int</span> code, String msg)&#123;<br>        <span class="hljs-built_in">this</span>.code = code;<br>        <span class="hljs-built_in">this</span>.msg = msg;<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 获取状态码</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> int</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-type">int</span> <span class="hljs-title function_">getCode</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> code;<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 获取信息</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> &#123;<span class="hljs-doctag">@link</span> String&#125;</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">getMsg</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> msg;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Slf4j</span><br><span class="hljs-meta">@RestControllerAdvice(basePackages = &quot;com.example.exceptiontest.controller&quot;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserExceptionControllerAdvice</span> &#123;<br>    <span class="hljs-meta">@ExceptionHandler(value = MethodArgumentNotValidException.class)</span><br>    <span class="hljs-keyword">public</span> Object <span class="hljs-title function_">handleValidException</span><span class="hljs-params">(MethodArgumentNotValidException e)</span>&#123;<br>        HashMap&lt;String, String&gt; map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>        <span class="hljs-type">BindingResult</span> <span class="hljs-variable">bindingResult</span> <span class="hljs-operator">=</span> e.getBindingResult();<br>        map.put(<span class="hljs-string">&quot;code&quot;</span>, String.valueOf(BizCodeEnume.VAILD_EXCEPTION.getCode()));<br>        bindingResult.getFieldErrors().forEach((item)-&gt;&#123;<br>            map.put(item.getField(),item.getDefaultMessage());<br>        &#125;);<br>        map.put(<span class="hljs-string">&quot;msg&quot;</span>,BizCodeEnume.VAILD_EXCEPTION.getMsg());<br>        log.error(<span class="hljs-string">&quot;数据校验出现异常:&#123;&#125;，异常类型:&#123;&#125;&quot;</span>,e.getMessage(),e.getClass());<br>        <span class="hljs-keyword">return</span> map;<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 处理最大的异常</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> e e</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> &#123;<span class="hljs-doctag">@link</span> Object&#125;</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@ExceptionHandler(value = Throwable.class)</span><br>    <span class="hljs-keyword">public</span> Object <span class="hljs-title function_">handleException</span><span class="hljs-params">(Throwable e)</span>&#123;<br>        HashMap&lt;String, String&gt; map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>        map.put(<span class="hljs-string">&quot;code&quot;</span>,String.valueOf(BizCodeEnume.UNKNOWN_EXCEPTION.getCode()));<br>        map.put(<span class="hljs-string">&quot;msg&quot;</span>,BizCodeEnume.UNKNOWN_EXCEPTION.getMsg());<br>        <span class="hljs-keyword">return</span> map;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181448835.png" srcset="/img/loading.gif" lazyload alt="image-20230218144806627"></p>
<h3 id="自定义异常"><a href="#自定义异常" class="headerlink" title="自定义异常"></a>自定义异常</h3><blockquote>
<p>注释掉之前写过的<code>@NotBlank(message = &quot;用户名不能为空&quot;)</code>…参数校验注解</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UsernameOrPasswordNULLException</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">RuntimeException</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">UsernameOrPasswordNULLException</span><span class="hljs-params">(String message)</span> &#123;<br>        <span class="hljs-built_in">super</span>(message);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 捕获UsernameOrPasswordNULLException异常</span><br><span class="hljs-meta">@ExceptionHandler(value = UsernameOrPasswordNULLException.class)</span><br><span class="hljs-keyword">public</span> Object <span class="hljs-title function_">usernameOrPasswordIsNull</span><span class="hljs-params">(UsernameOrPasswordNULLException e)</span>&#123;<br>    HashMap&lt;String, String&gt; map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>    <span class="hljs-comment">// 获取状态码</span><br>    map.put(<span class="hljs-string">&quot;code&quot;</span>, <span class="hljs-string">&quot;501&quot;</span>);<br>    <span class="hljs-comment">// 获取信息</span><br>    map.put(<span class="hljs-string">&quot;msg&quot;</span>,<span class="hljs-string">&quot;用户名或密码为空&quot;</span>);<br>    <span class="hljs-keyword">return</span> map;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@PostMapping(&quot;/test3&quot;)</span><br><span class="hljs-keyword">public</span> Object <span class="hljs-title function_">test3</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> User user)</span>&#123;<br>    String username=user.getUsername();<br>    String password=user.getPassword();<br>    <span class="hljs-keyword">if</span>(username==<span class="hljs-literal">null</span> || <span class="hljs-string">&quot;&quot;</span>.equals(username)||password==<span class="hljs-literal">null</span> ||<span class="hljs-string">&quot;&quot;</span>.equals(password))&#123;<br>        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">UsernameOrPasswordNULLException</span>(<span class="hljs-string">&quot;用户名或密码不能为空&quot;</span>);<br>    &#125;<br>    Map&lt;String, Object&gt; map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>    map.put(<span class="hljs-string">&quot;code&quot;</span>,<span class="hljs-number">200</span>);<br>    map.put(<span class="hljs-string">&quot;message&quot;</span>,user);<br>    <span class="hljs-keyword">return</span> map;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181508917.png" srcset="/img/loading.gif" lazyload alt="image-20230218150809676"></p>
<h2 id="分组校验"><a href="#分组校验" class="headerlink" title="分组校验"></a>分组校验</h2><blockquote>
<p>各个业务场景下的参数校验规则可能是不一样的<br>比如<code>新增用户</code>时，id字段自增，所以不需要填写，但<code>删除用户</code>时，id字段必须要填写</p>
<p>此时需要使用到<code>分组校验功能</code></p>
</blockquote>
<p>给注解标明，何时使用A校验规则，何时使用B校验规则</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 指定组AddGroup，新建AddGroup接口，什么都不用写;DeleteGroup 也一样</span><br><span class="hljs-meta">@Null(message = &quot;新增用户时，不能指定用户id&quot;,groups = &#123;AddGroup.class&#125;)</span><br><span class="hljs-meta">@NotNull(message = &quot;删除用户时，必须指定用户id&quot;,groups = &#123;DeleteGroup.class&#125;)</span><br><span class="hljs-meta">@TableId(value = &quot;id&quot;, type = IdType.AUTO)</span><br><span class="hljs-keyword">private</span> Integer id;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">AddGroup</span> &#123;<br>&#125;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">DeleteGroup</span> &#123;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181523120.png" srcset="/img/loading.gif" lazyload alt="image-20230218152344005"></p>
<blockquote>
<p>将<code>@Valid</code>注解 改为 <code>@Validated</code>注解</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@PostMapping(&quot;/save&quot;)</span><br><span class="hljs-keyword">public</span> Object <span class="hljs-title function_">saveUser</span><span class="hljs-params">(<span class="hljs-meta">@Validated(&#123;AddGroup.class&#125;)</span> <span class="hljs-meta">@RequestBody</span> User user)</span> &#123;<br>    <span class="hljs-type">boolean</span> <span class="hljs-variable">saveFlag</span> <span class="hljs-operator">=</span> userService.save(user);<br>    Map&lt;String, Object&gt; map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>    map.put(<span class="hljs-string">&quot;code&quot;</span>, <span class="hljs-number">200</span>);<br>    map.put(<span class="hljs-string">&quot;message&quot;</span>, saveFlag ? <span class="hljs-string">&quot;保存成功&quot;</span> : <span class="hljs-string">&quot;保存失败&quot;</span>);<br>    <span class="hljs-keyword">return</span> map;<br>&#125;<br><br><span class="hljs-meta">@DeleteMapping(&quot;/delete&quot;)</span><br><span class="hljs-keyword">public</span> Object <span class="hljs-title function_">deleteUser</span><span class="hljs-params">(<span class="hljs-meta">@Validated(&#123;DeleteGroup.class&#125;)</span> <span class="hljs-meta">@RequestBody</span> User user)</span> &#123;<br>    <span class="hljs-type">boolean</span> <span class="hljs-variable">saveFlag</span> <span class="hljs-operator">=</span> userService.removeById(user.getId());<br>    Map&lt;String, Object&gt; map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>    map.put(<span class="hljs-string">&quot;code&quot;</span>, <span class="hljs-number">200</span>);<br>    map.put(<span class="hljs-string">&quot;message&quot;</span>, saveFlag ? <span class="hljs-string">&quot;删除成功&quot;</span> : <span class="hljs-string">&quot;删除失败&quot;</span>);<br>    <span class="hljs-keyword">return</span> map;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>若校验注解如@NotNull不指定group，那么在执行方法时，会校验吗？</strong></p>
<p>答案是不会校验，不标注分组的校验注解是不起作用的</p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181534110.png" srcset="/img/loading.gif" lazyload alt="image-20230218153455850"></p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181535976.png" srcset="/img/loading.gif" lazyload alt="image-20230218153544904"></p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181536074.png" srcset="/img/loading.gif" lazyload alt="image-20230218153625006"></p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181536000.png" srcset="/img/loading.gif" lazyload alt="image-20230218153647928"></p>
<h2 id="自定义校验"><a href="#自定义校验" class="headerlink" title="自定义校验"></a>自定义校验</h2><blockquote>
<p>若<code>正则表达式</code>无法满足业务需求，需要自定义校验逻辑</p>
</blockquote>
<ol>
<li>编写自定义校验注解</li>
<li>编写自定义校验器</li>
<li>关联校验器和注解，让校验器来校验注解标注的字段</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@NickValue(vals=&#123;&quot;喜羊羊&quot;,&quot;灰太狼&quot;&#125;)</span><br><span class="hljs-meta">@TableField(value = &quot;nick_name&quot;)</span><br><span class="hljs-keyword">private</span> String nick_name;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> javax.validation.Constraint;<br><span class="hljs-keyword">import</span> javax.validation.Payload;<br><span class="hljs-keyword">import</span> java.lang.annotation.*;<br><br><span class="hljs-meta">@Documented</span><br><span class="hljs-comment">// 这里需要指定校验器，暂时先空着，等到后面再编写校验器</span><br><span class="hljs-meta">@Constraint(</span><br><span class="hljs-meta">        validatedBy = &#123;&#125;</span><br><span class="hljs-meta">)</span><br><span class="hljs-meta">@Target(&#123;ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE&#125;)</span><br><span class="hljs-meta">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> NickValue &#123;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 消息</span><br><span class="hljs-comment">     * 这里写该注解的全类名</span><br><span class="hljs-comment">     * 若校验失败，会前往ValidationMessages.properties来查询失败信息</span><br><span class="hljs-comment">     * 所以我们需要自己配置一个ValidationMessages.properties</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> &#123;<span class="hljs-doctag">@link</span> String&#125;</span><br><span class="hljs-comment">     */</span><br>    String <span class="hljs-title function_">message</span><span class="hljs-params">()</span> <span class="hljs-keyword">default</span> <span class="hljs-string">&quot;&#123;com.example.exceptiontest.valid.NickValue.message&#125;&quot;</span>;<br><br>    Class&lt;?&gt;[] groups() <span class="hljs-keyword">default</span> &#123;&#125;;<br><br>    Class&lt;? <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Payload</span>&gt;[] payload() <span class="hljs-keyword">default</span> &#123;&#125;;<br><br>    String[] vals() <span class="hljs-keyword">default</span> &#123;&#125;;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181554598.png" srcset="/img/loading.gif" lazyload alt="image-20230218155417292"></p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs properties"><span class="hljs-attr">com.example.exceptiontest.valid.NickValue.message</span>=<span class="hljs-string">昵称必须为指定的值</span><br></code></pre></td></tr></table></figure>

<p><strong>编写自定义校验器</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> javax.validation.ConstraintValidator;<br><span class="hljs-keyword">import</span> javax.validation.ConstraintValidatorContext;<br><span class="hljs-keyword">import</span> java.util.HashSet;<br><span class="hljs-keyword">import</span> java.util.Set;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 自定义昵称校验器</span><br><span class="hljs-comment"> * ConstraintValidator&lt;NickValue,String&gt; 前面为注解，后面为校验的字段类型</span><br><span class="hljs-comment"> * 如此时校验的字段是nickname，它的类型是String</span><br><span class="hljs-comment"> *</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@author</span> tong</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@date</span> 2023/02/18</span><br><span class="hljs-comment"> */</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">NickValueConstraintValidator</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">ConstraintValidator</span>&lt;NickValue,String&gt; &#123;<br>    <span class="hljs-keyword">private</span> Set&lt;String&gt; set=<span class="hljs-keyword">new</span> <span class="hljs-title class_">HashSet</span>&lt;String&gt;();<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 初始化</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> constraintAnnotation 约束注释</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">initialize</span><span class="hljs-params">(NickValue constraintAnnotation)</span> &#123;<br>        String[] vals = constraintAnnotation.vals();<br>        <span class="hljs-keyword">for</span> (String val : vals) &#123;<br>            set.add(val);<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 是否校验成功</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> s                          昵称</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> constraintValidatorContext 约束验证器上下文</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> boolean</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">isValid</span><span class="hljs-params">(String s, ConstraintValidatorContext constraintValidatorContext)</span> &#123;<br>        <span class="hljs-keyword">if</span>(set.contains(s))&#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>        &#125;<br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>别忘了在注解上添加对应的校验器</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Documented</span><br><span class="hljs-comment">// 添加对应的校验器</span><br><span class="hljs-meta">@Constraint(</span><br><span class="hljs-meta">        validatedBy = &#123;NickValueConstraintValidator.class&#125;</span><br><span class="hljs-meta">)</span><br><span class="hljs-meta">@Target(&#123;ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE&#125;)</span><br><span class="hljs-meta">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> NickValue &#123;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 消息</span><br><span class="hljs-comment">     * 这里写该注解的全类名</span><br><span class="hljs-comment">     * 若校验失败，会前往ValidationMessages.properties来查询失败信息</span><br><span class="hljs-comment">     * 所以我们需要自己配置一个ValidationMessages.properties</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> &#123;<span class="hljs-doctag">@link</span> String&#125;</span><br><span class="hljs-comment">     */</span><br>    String <span class="hljs-title function_">message</span><span class="hljs-params">()</span> <span class="hljs-keyword">default</span> <span class="hljs-string">&quot;&#123;com.example.exceptiontest.valid.NickValue.message&#125;&quot;</span>;<br><br>    Class&lt;?&gt;[] groups() <span class="hljs-keyword">default</span> &#123;&#125;;<br><br>    Class&lt;? <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Payload</span>&gt;[] payload() <span class="hljs-keyword">default</span> &#123;&#125;;<br><br>    String[] vals() <span class="hljs-keyword">default</span> &#123;&#125;;<br>&#125;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>打印一下错误信息</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@ExceptionHandler(value = Throwable.class)</span><br><span class="hljs-keyword">public</span> Object <span class="hljs-title function_">handleException</span><span class="hljs-params">(Throwable e)</span>&#123;<br>    <span class="hljs-comment">// 打印错误信息</span><br>    log.error(<span class="hljs-string">&quot;错误:&quot;</span>,e);<br>    HashMap&lt;String, String&gt; map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>    <span class="hljs-comment">// 获取状态码</span><br>    map.put(<span class="hljs-string">&quot;code&quot;</span>,String.valueOf(BizCodeEnume.UNKNOWN_EXCEPTION.getCode()));<br>    <span class="hljs-comment">// 获取信息</span><br>    map.put(<span class="hljs-string">&quot;msg&quot;</span>,BizCodeEnume.UNKNOWN_EXCEPTION.getMsg());<br>    <span class="hljs-keyword">return</span> map;<br>&#125;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>指定分组</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@NickValue(vals=&#123;&quot;喜羊羊&quot;,&quot;灰太狼&quot;&#125;,groups = &#123;AddGroup.class, DeleteGroup.class&#125;)</span><br><span class="hljs-meta">@TableField(value = &quot;nick_name&quot;)</span><br><span class="hljs-keyword">private</span> String nick_name;<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181612517.png" srcset="/img/loading.gif" lazyload alt="image-20230218161238324"></p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181612589.png" srcset="/img/loading.gif" lazyload alt="image-20230218161251523"></p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181613521.png" srcset="/img/loading.gif" lazyload alt="image-20230218161306450"></p>
<blockquote>
<p>校验注解指定多个校验器</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 这里可以添加多个校验器</span><br><span class="hljs-meta">@Constraint(</span><br><span class="hljs-meta">        validatedBy = &#123;NickValueConstraintValidator.class&#125;</span><br><span class="hljs-meta">)</span><br></code></pre></td></tr></table></figure>

<blockquote>
<p>此步骤参考<a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_37020594/article/details/122777649">博客</a></p>
<p>按住ctrl+H</p>
</blockquote>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181620912.png" srcset="/img/loading.gif" lazyload alt="image-20230218162021761"></p>
<p>可以看到存在很多校验器</p>
<blockquote>
<p>需要注意的<code>问题</code>如下</p>
</blockquote>
<p><strong>User</strong></p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181625320.png" srcset="/img/loading.gif" lazyload alt="image-20230218162537252"></p>
<p><strong>UserController</strong></p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202302181645029.png" srcset="/img/loading.gif" lazyload alt="image-20230218164538925"></p>
<blockquote>
<p>在修改用户的时候，我们是需要传入<code>密码</code>和<code>昵称</code>的</p>
<p>但是实际在个人主页修改个人昵称的时候，如果前端传递的user对象里只包含<code>用户id</code>和<code>昵称</code>而不包含密码，那么此时的校验无法通过<br>因为在<code>修改方法</code>内并未传入<code>密码</code><br>但是也无法删除<code>密码</code>注解的UpdateGroup，否则修改密码的时候如果不传入<code>密码</code>也能通过校验</p>
<p>原因是修改昵称和修改密码调用的是<code>同一个修改方法</code>和<code>同一个UpdateGroup</code></p>
<p>解决方法：<code>修改方法分开编写</code>，不要合并成同一个方法；同时创建一个新的修改分组，如<code>UpdateNiceNameGroup</code></p>
</blockquote>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E8%A1%A8%E5%8D%95%E6%A0%A1%E9%AA%8C-%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/" class="category-chain-item">表单校验+异常处理</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>表单校验+异常处理</div>
      <div>http://example.com/2023/02/18/编程语言/Java/学习/框架/SpringBoot/表单校验+异常处理/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>深海火锅店</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年2月18日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/02/25/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/Java/%E5%AD%A6%E4%B9%A0/%E6%A1%86%E6%9E%B6/Elasticsearct/Elasticsearch%E6%96%87%E6%A1%A3%E6%93%8D%E4%BD%9C/" title="Elasticsearch基础">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Elasticsearch基础</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/02/18/%E7%B3%BB%E7%BB%9F%E9%85%8D%E7%BD%AE/%E7%BC%96%E7%A8%8B%E9%85%8D%E7%BD%AE/%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE/Java%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F%E9%85%8D%E7%BD%AE/java%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F%E9%85%8D%E7%BD%AE/" title="Java环境变量配置">
                        <span class="hidden-mobile">Java环境变量配置</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="//cdn.jsdelivr.net/gh/EmoryHuang/BlogBeautify@1.1/DynamicRibbon.min.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
